
import json
import allure
import requests
import urllib3
from common.readyaml import ReadYamlData
from common.recordlog import logs
from conf import setting


class SendRequest:
    def __init__(self):
        self.read = ReadYamlData()
        self._session = None  # 使用类变量保存Session

    @property
    def get_session(self):
        """获取共享的Session（懒加载模式）"""
        if self._session is None:
            self._session = requests.Session()
            logs.info(f"session值：{self._session}")
            logs.debug("Created new session")
        return self._session

    def send_request(self,client,
            method,
            url,
            headers,
            cookies,
            files,
            timeout,
            verify,
            **kwargs):
        """发送请求（使用共享Session）"""
        try:
            if kwargs == {}:
                response = client.request(method=method,url=url,headers=headers,cookies=cookies,files=files,timeout=timeout,verify=verify)
            else:

                response = client.request(method=method, url=url, headers=headers, cookies=cookies, files=files,
                                          timeout=timeout, verify=verify,**kwargs)
            logs.info(
                f"请求成功"
                f"状态码: {response.status_code}\n响应内容: {response.text[:200]}..."
            )
            # 避免中文乱码
            response.encoding = 'utf-8'
            return response
        except requests.RequestException as e:
            logs.error(
                f"请求失败"
                f"错误: {str(e)}"
            )
            raise  # 重新抛出异常让调用方处理
    # def run_main(self, client,name, url, case_name, header, method, cookies=None, file=None, **kwargs):
    #     """
    #     统一请求入口
    #     :param name: 接口名
    #     :param url: 接口地址
    #     :param case_name: 测试用例名
    #     :param header: 请求头
    #     :param method: 请求方法
    #     :param cookies: Cookies
    #     :param file: 上传文件
    #     :param kwargs: 其他requests参数
    #     :return: Response对象
    #     """
    #     # 记录请求日志
    #     try:
    #         logs.info(f"接口名称：{name}")
    #         logs.info(f"请求地址：{url}")
    #         logs.info(f"请求方式：{method}")
    #         logs.info(f"测试用例：{case_name}")
    #         logs.info(f"请求头：{header}")
    #         logs.info(f"Cookies：{cookies}")
    #
    #
    #     except Exception as e:
    #         logs.error(f"日志记录错误：{e}")
    #
    #     # 禁用HTTPS警告
    #     urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    #
    #     # 发送请求
    #     try:
    #         result = client.request(method=method, url=url)
    #         result.encoding = 'utf-8'
    #         logs.error(f"000000000000000000000{result.json}")
    #         logs.error(type(result))
    #         logs.error(result.headers.get("Content-Type"))
    #         return result
    #
    #     except Exception as e:
    #         logs.error(f"3333333333{e}")
    def run_main(self, client,name, url, case_name, header, method, cookies=None, file=None, **kwargs):
        """
        统一请求入口
        :param name: 接口名
        :param url: 接口地址
        :param case_name: 测试用例名
        :param header: 请求头
        :param method: 请求方法
        :param cookies: Cookies
        :param file: 上传文件
        :param kwargs: 其他requests参数
        :return: Response对象
        """
        # 记录请求日志
        try:
            logs.info(f"接口名称：{name}")
            logs.info(f"请求地址：{url}")
            logs.info(f"请求方式：{method}")
            logs.info(f"测试用例：{case_name}")
            logs.info(f"请求头：{header}")
            logs.info(f"Cookies：{cookies}")
            if kwargs is not None and any(k in kwargs for k in ("data", "json", "params")):
                req_params = json.dumps(kwargs, ensure_ascii=False)
                allure.attach(req_params, "请求参数", allure.attachment_type.TEXT)
                logs.info(f"请求参数：{req_params}")
        except Exception as e:
            logs.error(f"日志记录错误：{e}")

        # 禁用HTTPS警告
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

        # 发送请求
        try:
            return self.send_request(client=client,
            method=method,
            url=url,
            headers=header,
            cookies=cookies,
            files=file,
            timeout=setting.API_TIMEOUT,
            verify=False,
            **kwargs
            )

        except Exception as e:
            logs.error(f"调用发送请求方法异常：{e}")
